/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.gridapps.nbgridftp.client;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;

import org.globus.ftp.DataChannelAuthentication;
import org.globus.ftp.FileInfo;

import cgl.narada.gridapps.nbgridftp.gridftpext.NBGridFTPClient;

/**
   @author Sang Boem Lim
   $Date$
   $Revision$
 */

public class RemoteDir extends JPanel implements MouseListener, 
    ActionListener{

    JList list = new JList();

    private static NBGridFTPClient curDir;
    JTextArea path;

    // those host name nad port number should be get from server.
    // list will not use NB.
    String host = "";
    int port = 2811;

    public RemoteDir() {
        //super(new GridLayout(2, 1));

        JPanel header = new JPanel();
        path = new JTextArea("Remote Directory...");
        path.setEditable(false);
        path.setColumns(10);
        path.setRows(1);
        JScrollPane scroll = new JScrollPane(path, 
                                      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
                                      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setBorder(new TitledBorder("Path"));
        
        JButton del = new JButton("del");
        del.setVerticalTextPosition(AbstractButton.CENTER);
        del.addActionListener(this);
        del.setActionCommand("delete");

        header.add(scroll);
        header.add(del);

        // Listen for events.
        list.addMouseListener(this);
        list.setFixedCellWidth(280);
        list.setFixedCellHeight(21);

        setFont(new Font("Monospaced", Font.PLAIN, 12));

        JPanel p1 = new JPanel();
        p1.add(new JScrollPane(list));
        p1.setBorder(new TitledBorder("Remote Dir"));

        add(header);
        add(p1);
    }	

    public void setup(String host, int port) {

        this.host = host;
        this.port = port;
    }

    private static String currentPath;
    public void display(String name){

        try {

            curDir = new NBGridFTPClient(host, port);
            curDir.authenticate(null);
            curDir.setDataChannelAuthentication(DataChannelAuthentication.NONE);

            Vector v;
            if (name == null) {
                
            } else if (name.equals("..")) {
                curDir.changeDir(currentPath);
                curDir.goUpDir();
            } else if (name.equals("NB/CONTROL")){
                curDir.changeDir(currentPath);
            } else {
                curDir.changeDir(currentPath + "/" + name);
            }
            
            // Get the filename in curDir.
            v = curDir.list();
            currentPath = curDir.getCurrentDir();
            
            if (v == null) v = new Vector();
            
            FileInfo[] files = new FileInfo[v.size()];
            String[] filenames = new String[v.size()];
            
            int index = 0;
            while (!v.isEmpty()) {
                files[index] = (FileInfo)v.remove(0);
                if(files[index].isDirectory())
                    filenames[index] = "+ " + files[index].getName();
                else 
                    filenames[index] = files[index].getName();
                
                index++;
            }
            
            // Update the list component with the new filenames..
            list.removeAll();
            
            v = new Vector();
            
            curDir.goUpDir();
            if (!(curDir.getCurrentDir()).equals(currentPath)) {
                v.add("..");
                curDir.changeDir(currentPath);
            }
            
            for (int i = 0; i < filenames.length; i++) {
                if (filenames[i] != null)
                    v.add(filenames[i]);
            }
            
            list.setListData(v);
            
            int offset = path.getLineEndOffset(0);
            path.replaceRange(currentPath, 0, offset);
            
            curDir.close();
        } catch (Exception e) {
            new Information().showError("Fail to list of remote directory.");
        }
    }

    public static String getCurrentDir() {

        return currentPath;
    }

    private void delete(String name, boolean isDir) {
        try {
            curDir = new NBGridFTPClient(host, port);
            curDir.authenticate(null);
            curDir.setDataChannelAuthentication(DataChannelAuthentication.NONE);

            if(isDir) curDir.deleteDir(currentPath + "/" + name);
            else curDir.deleteFile(currentPath + "/" + name);
            
            curDir.close();
        } catch (Exception e) {
            new Information().showError("Fail to list of remote directory.");
        }
    }
    
    public void actionPerformed(ActionEvent e) {
        if ("delete".equals(e.getActionCommand())) {
            int[] selected = list.getSelectedIndices();
            for (int i = 0; i < selected.length; i++) {
                String item = (String)list.getModel().getElementAt(selected[i]);
                if(item.startsWith("+ ")) {
                    delete(item.substring(2), true);
                } else if(!item.equals("..")) {
                    delete(item, false);
                }
            }

            display("NB/CONTROL");
        }
    }

    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            String item = (String)list.getModel().getElementAt(list.locationToIndex(e.getPoint()));

            if (item != null && (item.equals("..") || item.startsWith("+ "))) {
                if (item.startsWith("+ "))
                    item = item.substring(2);

                // If item is a directory, update he list.
                display(item);
            }
        }
    }

    public void mouseReleased(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    
}





